package cn.tedu.sp06zuul.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilteer extends ZuulFilter {
    //过滤器的类型: pre,routing,post,error
    @Override
    public String filterType() {
        //return pre;
        return FilterConstants.PRE_TYPE;
    }
    //过滤器的顺序号
    @Override
    public int filterOrder() {
        return 6; //默认已经有5个过滤器
    }
    //判断当前请求,是否需要执行下面的过滤代码
    @Override
    public boolean shouldFilter() {
        //调用商品,执行权限判断;
        //调用用户或者订单,不执行判断

        //获得当前请求的上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //从上下文对象,获得调用的 service id
        String serviceId = (String)ctx.get(FilterConstants.SERVICE_ID_KEY);
        //判断 service id 是否是 "item-service"
        return "item-service".equalsIgnoreCase(serviceId);
    }
    //过滤代码
    @Override
    public Object run() throws ZuulException {
        //http: //localhost:3001/item-service/i6juh65g4f3?jwt=dshkj324fd
         //获得当前请求的上下文对象
        RequestContext ctx = RequestContext.getCurrentContext();
        //从上下文得到request对象
        HttpServletRequest request = ctx.getRequest();
        //用request获取jwt参数
        String jwt = request.getParameter("jwt");
        //如果参数不存在，阻止继续调用，直接返回响应
        if (StringUtils.isBlank(jwt)){
            //阻止继续调用
            ctx.setSendZuulResponse(false);
            //直接返回响应
            String json = JsonResult.build().code(403).msg("没有登录").toString();
            ctx.addZuulResponseHeader("Content-Type","application/json;charset=utf-8");
            ctx.setResponseBody(json);
        }
        return null; //当前zuul版本中，这个返回值没有任何作用
    }
}
